//
//  CHUploadDataDetailController.m
//  CarFile
//
//  Created by 陈浩 on 2017/7/17.
//  Copyright © 2017年 陈浩. All rights reserved.
//

#import "CHUploadDataDetailController.h"
#import "CHUploadDataDetailCell.h"
#import "CHRepairDetailController.h"
#import "CHSearchView.h"
#import "CHPickerView.h"
@interface CHUploadDataDetailController ()<UITableViewDelegate ,UITableViewDataSource,CHSearchViewDelegate,ModuleProtocol,LongriseRouterDelegater>
@property (nonatomic ,strong) UITableView *tableView;
@property (nonatomic ,strong) NSMutableArray *datas;
@property (nonatomic ,strong) UILabel *titleLabel;
@property (nonatomic ,assign) int page;
@property (nonatomic ,assign) NSInteger year;
@property (nonatomic ,assign) NSInteger month;
@property (nonatomic ,strong) CHSearchView *searchView;
@property (nonatomic ,strong) UIButton *coverBtn;
@property (nonatomic ,strong) NSString *nameStr;
@end


@implementation CHUploadDataDetailController
-(NSMutableArray *)datas{
    if (!_datas) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = KRGB(239, 239, 249);
    self.title = @"上传数据质量详情";
    
    [self setupRightBarButtonItem];
    //   获取上一月
    [self getDateTime];
//    构建视图
    [self setupUI];
    
//    [super showLoading:YES];
//     获取数据
    [self getData];

}



-(void)setupRightBarButtonItem{
    
  
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.bounds = CGRectMake(0, 0, 40 ,15);
    btn.titleLabel.font = [UIFont systemFontOfSize:16];
    btn.titleLabel.textAlignment = NSTextAlignmentRight;
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    [btn setTitle:@"查找" forState:UIControlStateNormal];
    
    [btn addTarget:self action:@selector(seachBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    
}


-(void)seachBtnClick{
    
    if (!self.searchView) {
       
        UIButton *coverBtn = [[UIButton alloc] initWithFrame:self.view.bounds];
        coverBtn.backgroundColor = [UIColor blackColor];
        coverBtn.alpha = 0;
        [coverBtn addTarget:self action:@selector(coverBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:coverBtn];
        self.coverBtn = coverBtn;
        
        CHSearchView *searchView = [[CHSearchView alloc] initWithFrame:CGRectMake(0, -180, UIScreenW, 180)];
        searchView.delegate = self;
        [self.view addSubview:searchView];
        self.searchView = searchView;
        
        [UIView animateWithDuration:0.3 animations:^{
            
            searchView.frame = CGRectMake(0, 0, UIScreenW, 180);
            coverBtn.alpha = 0.5;
            
        }];
    }
 
}


-(void)dismiss{
    
    [UIView animateWithDuration:0.25 animations:^{
        
        self.searchView.frame = CGRectMake(0, -180, UIScreenW, 180);
        
    } completion:^(BOOL finished) {
        [self.searchView removeFromSuperview];
        [self.coverBtn removeFromSuperview];
        self.searchView = nil;
        self.coverBtn = nil;
    }];
    
    
}


-(void)coverBtnClick{
  
    [self dismiss];
   
}


#pragma mark - CHSearchDelegate
-(void)didSearchToDateStr:(NSString *)dateStr companyName:(NSString *)name{
    
    [self dismiss];
    
    _year = [[dateStr substringToIndex:4] integerValue];
    _month = [[dateStr substringFromIndex:5] integerValue];
    self.nameStr = name;

    [self getData];
    
}


-(void)getDateTime{
    
    NSDate  *currentDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy"];
    _year =[[formatter stringFromDate:currentDate] integerValue];
    [formatter setDateFormat:@"MM"];
    _month = [[formatter stringFromDate:currentDate] integerValue];
    
}


-(void)setupUI{
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, UIScreenW, 40)];
    titleLabel.font = [UIFont systemFontOfSize:12];
    titleLabel.textColor = [UIColor colorWithHexString:@"999999" alpha:1.0f];
    [self.view addSubview:titleLabel];
    self.titleLabel = titleLabel;
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40, UIScreenW, UIScreenH - 40 - 64)];
    self.tableView.backgroundColor = KRGB(239, 239, 249);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    // 下拉刷新
    self.tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        
        [self getData];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        [self loadMoreData];
    }];
    self.tableView.mj_footer.automaticallyHidden = YES;
    [self.view addSubview:self.tableView];
    
}


#pragma mark - 网络请求
-(void)getData{
    [MBProgressHUD showMessage:@"数据加载中..."];
    _page = 1;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = self.model.areaid;
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:self.model.areaid encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"year"] = [NSString stringWithFormat:@"%zd",_year];
    params[@"month"] = [NSString stringWithFormat:@"%zd",_month];
    params[@"pagesize"] = @"20";
    params[@"name"] = self.nameStr;
    params[@"pagenum"] = [NSString stringWithFormat:@"%d",_page];
    [[Globle getInstance].service requestWithServiceName:@"lcipappgovdataqualitylistinfo" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
        [self.datas removeAllObjects];
        NSLog(@"---->>%@",result);
        [MBProgressHUD hideHUD];
        [self.tableView.mj_header endRefreshing];
        if ([result[@"code"] isEqualToString:@"1"]) {
            if (![result[@"data"][@"totalnum"] isEqualToString:@"0"]) {
               
                for (NSDictionary *dict in result[@"data"][@"list"]) {
                    UploadDataModel *model = [[UploadDataModel alloc] init];
                    model.name = dict[@"name"];
                    model.areaid = dict[@"areaid"];
                    model.allscore = dict[@"allscore"];
                    model.datasize = dict[@"datasize"];
                    model.companyid = dict[@"companyid"];
                    model.carnonum = [NSString stringWithFormat:@"%@",dict[@"fullscore"][@"carnonum"]];
                    model.carvinnum = [NSString stringWithFormat:@"%@",dict[@"fullscore"][@"carvinnum"]];
                    model.nonum = [NSString stringWithFormat:@"%@",dict[@"normscore"][@"nonum"]];
                    model.vinnum = [NSString stringWithFormat:@"%@",dict[@"normscore"][@"vinnum"]];
                    [self.datas addObject:model];
                }
            }
            self.titleLabel.text = [NSString stringWithFormat:@"    %@有%@家企业完成系统对接",self.model.areacn,result[@"data"][@"totalnum"]];
            self.tableView.placeholderImage = @"data_null";
            self.tableView.placeholder = @"暂时没有数据哦~";
            [self.tableView reloadData];
        }
    }];
}

//  加载更多
-(void)loadMoreData{
    _page++;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = self.model.areaid;
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:self.model.areaid encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"year"] = [NSString stringWithFormat:@"%zd",_year];
    params[@"month"] = [NSString stringWithFormat:@"%zd",_month];
    params[@"pagesize"] = @"20";
    params[@"pagenum"] = [NSString stringWithFormat:@"%d",_page];
    [[Globle getInstance].service requestWithServiceName:@"lcipappgovdataqualitylistinfo" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
        

        [super showLoading:NO];
        [self.tableView.mj_footer endRefreshing];
        if ([result[@"code"] isEqualToString:@"1"]) {
            for (NSDictionary *dict in result[@"data"][@"list"]) {
                UploadDataModel *model = [[UploadDataModel alloc] init];
                model.name = dict[@"name"];
                model.allscore = dict[@"allscore"];
                model.datasize = dict[@"datasize"];
                model.companyid = dict[@"companyid"];
                model.carnonum = [NSString stringWithFormat:@"%@",dict[@"fullscore"][@"carnonum"]];
                model.carvinnum = [NSString stringWithFormat:@"%@",dict[@"fullscore"][@"carvinnum"]];
                model.nonum = [NSString stringWithFormat:@"%@",dict[@"normscore"][@"nonum"]];
                model.vinnum = [NSString stringWithFormat:@"%@",dict[@"normscore"][@"vinnum"]];
                [self.datas addObject:model];
            }
      
            [self.tableView reloadData];
        }
    }];

    
    
    
}



#pragma mark - UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.datas.count;
    
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CHUploadDataDetailCell *cell = [CHUploadDataDetailCell cellForTableView:tableView];
    cell.model = self.datas[indexPath.row];
    return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 200;
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    
    id obj = [LongriseRouter openURL:@"CHRepairDetailController"];
    if(obj && [obj isKindOfClass:[UIViewController class]])
    {
        UIViewController *vc = obj;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    //判断该类是否可以传参数
    if([LongriseRouter isImplLongriseRouterDelegaterWithObject:obj])
    {
        id<LongriseRouterDelegater> delegater = obj;
        if(delegater)
        {
            
            UploadDataModel *model = self.datas[indexPath.row];
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            
            params[@"companyid"] = model.companyid;
            params[@"areaid"] = model.areaid;
            
            //进行传值，传入统一的block以供B进行回调
            [delegater setParams:params block:^(id obj) {
                
                
            }];
        }
    }
    
}

#pragma mark LongriseRouterDelegater代理回调方法
-(void)setParams:(id)obj block:(LongriseRouterBlock)block
{
    if (obj && [obj isKindOfClass:[UploadDataModel class]]) {
        UploadDataModel *model = obj;
        self.model = model;
    }
}

#pragma mark ModuleProtocol代理回调方法
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //处理需要初始化的东西，比如这个是地图模块，这里就实现地图的初始化
    NSLog(@"ModuleViewController2的didFinishLaunchingWithOptions方法被调用了");
    return false;
}


@end
